<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>蓝忘机AI</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Microsoft YaHei", sans-serif;
        }
        
        body {
            background-color: #e6f7ff;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            position: relative;
            overflow: hidden;
        }
        
        body::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="400" height="600" viewBox="0 0 400 600"><rect width="400" height="600" fill="%23e6f7ff"/><path d="M0,300 Q100,250 200,300 Q300,350 400,300 L400,600 L0,600 Z" fill="%23bbdefb" opacity="0.3"/></svg>');
            background-size: cover;
            background-position: center;
            z-index: -1;
            mask-image: linear-gradient(to bottom, rgba(0,0,0,0.3) 0%, rgba(0,0,0,0) 10%, rgba(0,0,0,0) 90%, rgba(0,0,0,0.3) 100%);
        }
        
        .chat-container {
            width: 400px;
            height: 600px;
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            position: relative;
        }
        
        .chat-header {
            height: 70px;
            background: linear-gradient(135deg, #1e88e5, #0d47a1);
            color: white;
            display: flex;
            align-items: center;
            padding: 0 20px;
            position: relative;
        }
        
        .back-button {
            font-size: 20px;
            margin-right: 15px;
            cursor: pointer;
        }
        
        .chat-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background-color: #bbdefb;
            margin-right: 15px;
            overflow: hidden;
            border: 2px solid white;
            cursor: pointer;
        }
        
        .chat-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .chat-info {
            flex: 1;
        }
        
        .chat-name {
            font-size: 18px;
            font-weight: bold;
        }
        
        .chat-status {
            font-size: 12px;
            opacity: 0.9;
        }
        
        .settings-button {
            font-size: 20px;
            margin-left: 15px;
            cursor: pointer;
            position: relative;
        }
        
        .settings-button:hover::after {
            content: '设置';
            position: absolute;
            top: -25px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #333;
            color: white;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
        }
        
        .chat-messages {
            flex: 1;
            padding: 15px;
            overflow-y: auto;
            background-color: rgba(245, 249, 255, 0.7);
        }
        
        .message {
            margin-bottom: 25px;
            display: flex;
            flex-direction: column;
            max-width: 80%;
            position: relative;
        }
        
        .user-message {
            align-items: flex-end;
            margin-left: auto;
        }
        
        .ai-message {
            align-items: flex-start;
            margin-right: auto;
        }
        
        .message-avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: #e3f2fd;
            margin-right: 10px;
            overflow: hidden;
            position: absolute;
            left: 0;
            top: -35px;
            cursor: pointer;
            border: 1px solid #bbdefb;
        }
        
        .message-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .user-message .message-avatar {
            left: auto;
            right: 0;
            background-color: #f5f5f5;
        }
        
        .message-content {
            padding: 12px 15px;
            border-radius: 18px;
            margin-top: 5px;
            position: relative;
            word-wrap: break-word;
            line-height: 1.5;
        }
        
        .user-message .message-content {
            background-color: #e3f2fd;
            color: #0d47a1;
            border-top-right-radius: 5px;
        }
        
        .ai-message .message-content {
            background-color: white;
            color: #333;
            border: 1px solid #bbdefb;
            border-top-left-radius: 5px;
        }
        
        .message-time {
            font-size: 11px;
            color: #78909c;
            margin-top: 3px;
        }
        
        .message-actions {
            position: absolute;
            bottom: -20px;
            right: 0;
            display: none;
        }
        
        .user-message .message-actions {
            left: auto;
            right: 0;
        }
        
        .message:hover .message-actions {
            display: flex;
        }
        
        .action-button {
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-left: 5px;
            cursor: pointer;
            font-size: 12px;
            color: #555;
            border: 1px solid #ddd;
            position: relative;
        }
        
        .action-button:hover::after {
            content: attr(data-tooltip);
            position: absolute;
            top: -25px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #333;
            color: white;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
        }
        
        .refresh-button {
            position: absolute;
            bottom: -20px;
            right: 0;
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            font-size: 12px;
            color: #555;
            border: 1px solid #ddd;
            position: relative;
        }
        
        .refresh-button:hover::after {
            content: '重新生成';
            position: absolute;
            top: -25px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #333;
            color: white;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
        }
        
        .refresh-button.loading {
            animation: spin 1s linear infinite;
        }
        
        .back-button {
            position: absolute;
            bottom: -20px;
            right: 30px;
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            font-size: 12px;
            color: #555;
            border: 1px solid #ddd;
            position: relative;
        }
        
        .back-button:hover::after {
            content: '回溯对话';
            position: absolute;
            top: -25px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #333;
            color: white;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .chat-input {
            height: 70px;
            background-color: white;
            display: flex;
            align-items: center;
            padding: 0 15px;
            border-top: 1px solid #e0e0e0;
        }
        
        .message-input {
            flex: 1;
            height: 40px;
            border: 1px solid #bbdefb;
            border-radius: 20px;
            padding: 0 15px;
            outline: none;
            background-color: #f5f9ff;
        }
        
        .send-button {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #1e88e5, #0d47a1);
            color: white;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-left: 10px;
            cursor: pointer;
            border: none;
            position: relative;
        }
        
        .send-button:hover::after {
            content: '发送';
            position: absolute;
            top: -25px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #333;
            color: white;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
        }
        
        .typing-indicator {
            display: flex;
            align-items: center;
            margin-left: 15px;
        }
        
        .typing-dot {
            width: 8px;
            height: 8px;
            background-color: #0d47a1;
            border-radius: 50%;
            margin: 0 2px;
            animation: typing 1.4s infinite ease-in-out;
        }
        
        .typing-dot:nth-child(1) {
            animation-delay: 0s;
        }
        
        .typing-dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .typing-dot:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        @keyframes typing {
            0%, 60%, 100% {
                transform: translateY(0);
            }
            30% {
                transform: translateY(-5px);
            }
        }
        
        .cloud {
            position: absolute;
            width: 100px;
            height: 50px;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50"><path d="M20,30 Q30,10 50,10 Q70,10 80,30 Q90,30 90,40 Q90,50 80,50 L20,50 Q10,50 10,40 Q10,30 20,30" fill="%23bbdefb" opacity="0.6"/></svg>');
            background-size: contain;
            background-repeat: no-repeat;
            z-index: 0;
            pointer-events: none;
            animation: float 30s linear infinite;
        }
        
        @keyframes float {
            0% {
                transform: translateX(-100px) translateY(0);
                opacity: 0;
            }
            10% {
                opacity: 0.6;
            }
            90% {
                opacity: 0.6;
            }
            100% {
                transform: translateX(500px) translateY(20px);
                opacity: 0;
            }
        }
        
        .guqin {
            position: absolute;
            width: 40px;
            height: 40px;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect x="20" y="40" width="60" height="10" rx="2" fill="%238bc34a"/><rect x="25" y="35" width="50" height="5" rx="2" fill="%235d4037"/><line x1="30" y1="30" x2="30" y2="70" stroke="%235d4037" stroke-width="2"/><line x1="70" y1="30" x2="70" y2="70" stroke="%235d4037" stroke-width="2"/><line x1="40" y1="45" x2="40" y2="55" stroke="%235d4037" stroke-width="1"/><line x1="50" y1="45" x2="50" y2="55" stroke="%235d4037" stroke-width="1"/><line x1="60" y1="45" x2="60" y2="55" stroke="%235d4037" stroke-width="1"/></svg>');
            background-size: contain;
            z-index: 0;
            pointer-events: none;
            animation: floatGuqin 20s linear infinite;
        }
        
        @keyframes floatGuqin {
            0% {
                transform: translateX(-50px) translateY(0) rotate(0deg);
                opacity: 0;
            }
            10% {
                opacity: 0.8;
            }
            90% {
                opacity: 0.8;
            }
            100% {
                transform: translateX(450px) translateY(100px) rotate(360deg);
                opacity: 0;
            }
        }
        
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 100;
        }
        
        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            width: 80%;
            max-width: 300px;
            max-height: 80vh;
            overflow-y: auto;
        }
        
        .modal-title {
            color: #0d47a1;
            margin-bottom: 15px;
            text-align: center;
        }
        
        .avatar-options {
            display: flex;
            justify-content: space-around;
            margin: 15px 0;
            flex-wrap: wrap;
        }
        
        .avatar-option {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            overflow: hidden;
            cursor: pointer;
            border: 3px solid transparent;
            margin: 5px;
        }
        
        .avatar-option.selected {
            border-color: #1e88e5;
        }
        
        .avatar-option img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .modal-actions {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
            flex-wrap: wrap;
        }
        
        .modal-button {
            padding: 8px 15px;
            border-radius: 20px;
            border: none;
            cursor: pointer;
            margin: 5px;
            flex-grow: 1;
            text-align: center;
        }
        
        .upload-button {
            background-color: #bbdefb;
            color: #0d47a1;
        }
        
        .save-button {
            background-color: #1e88e5;
            color: white;
        }
        
        .delete-button {
            background-color: #e53935;
            color: white;
        }
        
        .cancel-button {
            background-color: #e0e0e0;
            color: #333;
        }
        
        .identity-form {
            margin-top: 15px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-size: 14px;
        }
        
        .form-input, .form-select {
            width: 100%;
            padding: 8px;
            border: 1px solid #bbdefb;
            border-radius: 4px;
        }
        
        .response-options {
            margin-top: 10px;
            border-top: 1px dashed #bbdefb;
            padding-top: 10px;
        }
        
        .response-option {
            background-color: #e3f2fd;
            padding: 8px;
            margin-bottom: 5px;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .response-option:hover {
            background-color: #bbdefb;
        }
        
        .ai-thought {
            font-size: 12px;
            color: #78909c;
            font-style: italic;
            margin-top: 5px;
        }
        
        .narration {
            font-size: 12px;
            color: #666;
            font-style: italic;
            margin: 10px 0;
            text-align: center;
            width: 100%;
        }
        
        .settings-panel {
            position: absolute;
            top: 70px;
            right: 10px;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.2);
            padding: 10px;
            width: 200px;
            z-index: 10;
            display: none;
        }
        
        .settings-item {
            padding: 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            border-radius: 4px;
        }
        
        .settings-item:hover {
            background-color: #f5f5f5;
        }
        
        .settings-item i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }
        
        .music-controls {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }
        
        .volume-control {
            width: 100%;
            margin-top: 10px;
        }
        
        .character-settings {
            margin-top: 15px;
        }
        
        .character-textarea {
            width: 100%;
            height: 100px;
            padding: 8px;
            border: 1px solid #bbdefb;
            border-radius: 4px;
            resize: vertical;
        }
        
        .bg-options {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;
            margin: 15px 0;
        }
        
        .bg-option {
            width: 80px;
            height: 60px;
            border-radius: 5px;
            overflow: hidden;
            cursor: pointer;
            border: 3px solid transparent;
            margin: 5px;
        }
        
        .bg-option.selected {
            border-color: #1e88e5;
        }
        
        .bg-option img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .avatar-viewer {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 100;
        }
        
        .avatar-viewer-content {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            width: 80%;
            max-width: 300px;
            text-align: center;
        }
        
        .avatar-viewer-img {
            width: 200px;
            height: 200px;
            border-radius: 50%;
            margin: 0 auto 20px;
            overflow: hidden;
            border: 3px solid #bbdefb;
        }
        
        .avatar-viewer-img img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <div class="chat-avatar" id="ai-avatar">
                <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><circle cx='50' cy='40' r='20' fill='%23bbdefb'/><path d='M30,70 Q50,90 70,70' fill='%23bbdefb'/><rect x='40' y='30' width='20' height='5' fill='%230d47a1'/><rect x='35' y='50' width='30' height='5' fill='%230d47a1'/><path d='M40,25 Q50,15 60,25' fill='none' stroke='%230d47a1' stroke-width='2'/><circle cx='40' cy='35' r='3' fill='%230d47a1'/><circle cx='60' cy='35' r='3' fill='%230d47a1'/></svg>">
            </div>
            <div class="chat-info">
                <div class="chat-name">蓝忘机</div>
                <div class="chat-status" id="chat-status">在线</div>
            </div>
            <div class="typing-indicator" id="typing-indicator" style="display: none;">
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
            </div>
            <div class="settings-button" onclick="toggleSettings()">
                <i class="fas fa-ellipsis-v"></i>
            </div>
            <div class="settings-panel" id="settings-panel">
                <div class="settings-item" onclick="openIdentityModal()">
                    <i class="fas fa-user"></i> 身份设置
                </div>
                <div class="settings-item" onclick="openAvatarModal('user')">
                    <i class="fas fa-user-edit"></i> 修改头像
                </div>
                <div class="settings-item" onclick="openAvatarModal('ai')">
                    <i class="fas fa-robot"></i> 修改蓝忘机头像
                </div>
                <div class="settings-item" onclick="openBgModal()">
                    <i class="fas fa-image"></i> 修改背景
                </div>
                <div class="settings-item" onclick="openMusicModal()">
                    <i class="fas fa-music"></i> 背景音乐
                </div>
                <div class="settings-item" onclick="openCharacterModal()">
                    <i class="fas fa-book"></i> 蓝忘机人设
                </div>
            </div>
        </div>
        <div class="chat-messages" id="chat-messages">
            <!-- 初始消息 -->
            <div class="narration">
                （云深不知处，清晨的阳光透过竹林洒在静室前，微风拂过，带来阵阵竹叶清香）
            </div>
            <div class="message ai-message" data-id="1">
                <div class="message-avatar" onclick="viewAvatar(aiData.avatar)">
                    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><circle cx='50' cy='40' r='20' fill='%23bbdefb'/><path d='M30,70 Q50,90 70,70' fill='%23bbdefb'/><rect x='40' y='30' width='20' height='5' fill='%230d47a1'/><rect x='35' y='50' width='30' height='5' fill='%230d47a1'/><path d='M40,25 Q50,15 60,25' fill='none' stroke='%230d47a1' stroke-width='2'/><circle cx='40' cy='35' r='3' fill='%230d47a1'/><circle cx='60' cy='35' r='3' fill='%230d47a1'/></svg>">
                </div>
                <div class="message-content">
                    嗯。（微微颔首）<br>
                    在下姑苏蓝氏蓝忘机，字忘机。
                    <div class="ai-thought">（看来是一位新访客...）</div>
                </div>
                <div class="message-time">刚刚</div>
                <div class="back-button" onclick="backToMessage(this.parentElement.dataset.id)">
                    <i class="fas fa-undo"></i>
                </div>
                <div class="refresh-button" onclick="regenerateResponse(this.parentElement.dataset.id)">
                    <i class="fas fa-redo"></i>
                </div>
            </div>
        </div>
        <div class="chat-input">
            <input type="text" class="message-input" id="message-input" placeholder="输入消息..." onkeypress="handleKeyPress(event)">
            <button class="send-button" onclick="sendMessage()">
                <i class="fas fa-paper-plane"></i>
            </button>
        </div>
    </div>

    <!-- 头像查看器 -->
    <div class="avatar-viewer" id="avatar-viewer">
        <div class="avatar-viewer-content">
            <div class="avatar-viewer-img">
                <img id="viewer-img" src="">
            </div>
            <div class="modal-actions">
                <button class="modal-button upload-button" onclick="document.getElementById('avatar-upload').click()">
                    <i class="fas fa-upload"></i> 上传
                </button>
                <button class="modal-button delete-button" onclick="deleteCurrentAvatar()">
                    <i class="fas fa-trash"></i> 删除
                </button>
                <button class="modal-button cancel-button" onclick="closeModal('avatar-viewer')">
                    <i class="fas fa-times"></i> 关闭
                </button>
            </div>
            <input type="file" id="avatar-upload" style="display: none;" accept="image/*">
        </div>
    </div>

    <!-- 头像选择模态框 -->
    <div class="modal" id="avatar-modal">
        <div class="modal-content">
            <h3 class="modal-title" id="avatar-modal-title">选择头像</h3>
            <div class="avatar-options">
                <div class="avatar-option selected" onclick="selectAvatar(this, 'user')">
                    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><circle cx='50' cy='40' r='20' fill='%23e3f2fd'/><path d='M30,70 Q50,90 70,70' fill='%23e3f2fd'/><rect x='40' y='30' width='20' height='5' fill='%230d47a1'/><rect x='35' y='50' width='30' height='5' fill='%230d47a1'/><path d='M40,25 Q50,15 60,25' fill='none' stroke='%230d47a1' stroke-width='2'/><circle cx='40' cy='35' r='3' fill='%230d47a1'/><circle cx='60' cy='35' r='3' fill='%230d47a1'/></svg>">
                </div>
                <div class="avatar-option" onclick="selectAvatar(this, 'user')">
                    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><circle cx='50' cy='40' r='20' fill='%23e3f2fd'/><path d='M30,70 Q50,80 70,70' fill='%23e3f2fd'/><rect x='40' y='30' width='20' height='5' fill='%230d47a1'/><rect x='35' y='50' width='30' height='5' fill='%230d47a1'/><path d='M40,25 Q50,20 60,25' fill='none' stroke='%230d47a1' stroke-width='2'/><circle cx='40' cy='35' r='3' fill='%230d47a1'/><circle cx='60' cy='35' r='3' fill='%230d47a1'/></svg>">
                </div>
                <div class="avatar-option" onclick="selectAvatar(this, 'user')">
                    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><circle cx='50' cy='40' r='20' fill='%23e3f2fd'/><path d='M30,70 Q50,85 70,70' fill='%23e3f2fd'/><rect x='40' y='30' width='20' height='5' fill='%230d47a1'/><rect x='35' y='50' width='30' height='5' fill='%230d47a1'/><path d='M40,25 Q50,18 60,25' fill='none' stroke='%230d47a1' stroke-width='2'/><circle cx='40' cy='35' r='3' fill='%230d47a1'/><circle cx='60' cy='35' r='3' fill='%230d47a1'/></svg>">
                </div>
            </div>
            <div class="modal-actions">
                <button class="modal-button upload-button" onclick="uploadAvatar('user')">
                    <i class="fas fa-upload"></i> 上传
                </button>
                <button class="modal-button save-button" onclick="saveAvatar('user')">
                    <i class="fas fa-save"></i> 保存
                </button>
                <button class="modal-button delete-button" onclick="deleteAvatar('user')">
                    <i class="fas fa-trash"></i> 删除
                </button>
                <button class="modal-button cancel-button" onclick="closeModal('avatar-modal')">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
            <input type="file" id="user-avatar-upload" style="display: none;" accept="image/*">
        </div>
    </div>

    <!-- AI头像选择模态框 -->
    <div class="modal" id="ai-avatar-modal">
        <div class="modal-content">
            <h3 class="modal-title">选择蓝忘机头像</h3>
            <div class="avatar-options">
                <div class="avatar-option selected" onclick="selectAvatar(this, 'ai')">
                    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><circle cx='50' cy='40' r='20' fill='%23bbdefb'/><path d='M30,70 Q50,90 70,70' fill='%23bbdefb'/><rect x='40' y='30' width='20' height='5' fill='%230d47a1'/><rect x='35' y='50' width='30' height='5' fill='%230d47a1'/><path d='M40,25 Q50,15 60,25' fill='none' stroke='%230d47a1' stroke-width='2'/><circle cx='40' cy='35' r='3' fill='%230d47a1'/><circle cx='60' cy='35' r='3' fill='%230d47a1'/></svg>">
                </div>
                <div class="avatar-option" onclick="selectAvatar(this, 'ai')">
                    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><circle cx='50' cy='50' r='45' fill='%231e88e5'/><path d='M30,70 Q50,90 70,70' fill='%231e88e5'/><rect x='40' y='30' width='20' height='5' fill='%23fff'/><rect x='35' y='50' width='30' height='5' fill='%23fff'/><path d='M40,25 Q50,15 60,25' fill='none' stroke='%23fff' stroke-width='2'/><circle cx='40' cy='35' r='3' fill='%23fff'/><circle cx='60' cy='35' r='3' fill='%23fff'/></svg>">
                </div>
                <div class="avatar-option" onclick="selectAvatar(this, 'ai')">
                    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><circle cx='50' cy='40' r='20' fill='%23bbdefb'/><path d='M30,70 Q50,85 70,70' fill='%23bbdefb'/><rect x='40' y='30' width='20' height='5' fill='%230d47a1'/><rect x='35' y='50' width='30' height='5' fill='%230d47a1'/><path d='M40,25 Q50,18 60,25' fill='none' stroke='%230d47a1' stroke-width='2'/><circle cx='40' cy='35' r='3' fill='%230d47a1'/><circle cx='60' cy='35' r='3' fill='%230d47a1'/></svg>">
                </div>
            </div>
            <div class="modal-actions">
                <button class="modal-button upload-button" onclick="uploadAvatar('ai')">
                    <i class="fas fa-upload"></i> 上传
                </button>
                <button class="modal-button save-button" onclick="saveAvatar('ai')">
                    <i class="fas fa-save"></i> 保存
                </button>
                <button class="modal-button delete-button" onclick="deleteAvatar('ai')">
                    <i class="fas fa-trash"></i> 删除
                </button>
                <button class="modal-button cancel-button" onclick="closeModal('ai-avatar-modal')">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
            <input type="file" id="ai-avatar-upload" style="display: none;" accept="image/*">
        </div>
    </div>

    <!-- 用户身份设置模态框 -->
    <div class="modal" id="identity-modal">
        <div class="modal-content">
            <h3 class="modal-title">设置身份</h3>
            <div class="avatar-options">
                <div class="avatar-option selected" onclick="selectAvatar(this, 'user')">
                    <img id="user-avatar-preview" src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><circle cx='50' cy='40' r='20' fill='%23e3f2fd'/><path d='M30,70 Q50,90 70,70' fill='%23e3f2fd'/><rect x='40' y='30' width='20' height='5' fill='%230d47a1'/><rect x='35' y='50' width='30' height='5' fill='%230d47a1'/><path d='M40,25 Q50,15 60,25' fill='none' stroke='%230d47a1' stroke-width='2'/><circle cx='40' cy='35' r='3' fill='%230d47a1'/><circle cx='60' cy='35' r='3' fill='%230d47a1'/></svg>">
                </div>
            </div>
            <div class="identity-form">
                <div class="form-group">
                    <label class="form-label">你的名字</label>
                    <input type="text" class="form-input" id="user-name" placeholder="输入你的名字">
                </div>
                <div class="form-group">
                    <label class="form-label">你的身份</label>
                    <select class="form-select" id="user-identity">
                        <option value="">自定义身份</option>
                        <option value="姑苏蓝氏弟子">姑苏蓝氏弟子</option>
                        <option value="云梦江氏弟子">云梦江氏弟子</option>
                        <option value="兰陵金氏弟子">兰陵金氏弟子</option>
                        <option value="清河聂氏弟子">清河聂氏弟子</option>
                        <option value="岐山温氏弟子">岐山温氏弟子</option>
                        <option value="散修">散修</option>
                        <option value="普通百姓">普通百姓</option>
                        <option value="魏无羡">魏无羡</option>
                    </select>
                    <input type="text" class="form-input" id="custom-identity" placeholder="或输入自定义身份" style="margin-top: 5px; display: none;">
                </div>
            </div>
            <div class="modal-actions">
                <button class="modal-button upload-button" onclick="uploadAvatar('user')">
                    <i class="fas fa-upload"></i> 上传头像
                </button>
                <button class="modal-button save-button" onclick="saveIdentity()">
                    <i class="fas fa-save"></i> 保存
                </button>
                <button class="modal-button cancel-button" onclick="closeModal('identity-modal')">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
            <input type="file" id="user-avatar-upload" style="display: none;" accept="image/*">
        </div>
    </div>

    <!-- 背景设置模态框 -->
    <div class="modal" id="bg-modal">
        <div class="modal-content">
            <h3 class="modal-title">选择背景</h3>
            <div class="bg-options">
                <div class="bg-option selected" onclick="selectBg(this, 'default')">
                    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='400' height='600' viewBox='0 0 400 600'><rect width='400' height='600' fill='%23e6f7ff'/><path d='M0,300 Q100,250 200,300 Q300,350 400,300 L400,600 L0,600 Z' fill='%23bbdefb' opacity='0.3'/></svg>">
                </div>
                <div class="bg-option" onclick="selectBg(this, 'cloud')">
                    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='400' height='600' viewBox='0 0 400 600'><rect width='400' height='600' fill='%23e3f2fd'/><path d='M50,150 Q150,100 250,150 Q350,200 400,150 L400,600 L0,600 Z' fill='%23bbdefb' opacity='0.5'/><circle cx='100' cy='100' r='50' fill='%23bbdefb' opacity='0.3'/><circle cx='300' cy='120' r='70' fill='%23bbdefb' opacity='0.3'/></svg>">
                </div>
                <div class="bg-option" onclick="selectBg(this, 'bamboo')">
                    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='400' height='600' viewBox='0 0 400 600'><rect width='400' height='600' fill='%23e6f7ff'/><rect x='50' y='0' width='10' height='600' fill='%238bc34a' opacity='0.5'/><rect x='150' y='0' width='10' height='600' fill='%238bc34a' opacity='0.5'/><rect x='250' y='0' width='10' height='600' fill='%238bc34a' opacity='0.5'/><rect x='350' y='0' width='10' height='600' fill='%238bc34a' opacity='0.5'/></svg>">
                </div>
            </div>
            <div class="modal-actions">
                <button class="modal-button upload-button" onclick="uploadBg()">
                    <i class="fas fa-upload"></i> 上传
                </button>
                <button class="modal-button save-button" onclick="saveBg()">
                    <i class="fas fa-save"></i> 保存
                </button>
                <button class="modal-button delete-button" onclick="deleteBg()">
                    <i class="fas fa-trash"></i> 删除
                </button>
                <button class="modal-button cancel-button" onclick="closeModal('bg-modal')">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
            <input type="file" id="bg-upload" style="display: none;" accept="image/*">
        </div>
    </div>

    <!-- 音乐设置模态框 -->
    <div class="modal" id="music-modal">
        <div class="modal-content">
            <h3 class="modal-title">背景音乐</h3>
            <div class="form-group">
                <label class="form-label">选择音乐</label>
                <select class="form-select" id="music-select">
                    <option value="none">无</option>
                    <option value="guqin">古琴曲 - 高山流水</option>
                    <option value="xiao">箫曲 - 梅花三弄</option>
                    <option value="pipa">琵琶曲 - 十面埋伏</option>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">播放模式</label>
                <select class="form-select" id="music-mode">
                    <option value="loop">循环播放</option>
                    <option value="once">播放一次</option>
                    <option value="sequence">顺序播放</option>
                </select>
            </div>
            <div class="music-controls">
                <div style="display: flex; align-items: center;">
                    <button class="modal-button" id="play-music" style="margin-right: 10px;">
                        <i class="fas fa-play"></i> 播放
                    </button>
                    <button class="modal-button" id="pause-music">
                        <i class="fas fa-pause"></i> 暂停
                    </button>
                </div>
                <div class="form-group" style="margin-top: 10px;">
                    <label class="form-label">音量</label>
                    <input type="range" class="volume-control" id="volume-control" min="0" max="1" step="0.1" value="0.5">
                </div>
            </div>
            <div class="modal-actions">
                <button class="modal-button save-button" onclick="saveMusicSettings()">
                    <i class="fas fa-save"></i> 保存
                </button>
                <button class="modal-button cancel-button" onclick="closeModal('music-modal')">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
            <audio id="bg-music" loop>
                <source id="music-source" type="audio/mpeg">
            </audio>
        </div>
    </div>

    <!-- 角色设置模态框 -->
    <div class="modal" id="character-modal">
        <div class="modal-content">
            <h3 class="modal-title">蓝忘机人设</h3>
            <div class="character-settings">
                <p>蓝忘机，字忘机，号含光君，姑苏蓝氏二公子。为人清冷严肃，不苟言笑，恪守家规，雅正端方。佩剑避尘，法器忘机琴。与魏无羡关系密切。</p>
                <div class="form-group">
                    <label class="form-label">补充人设信息</label>
                    <textarea class="character-textarea" id="character-info" placeholder="可以补充蓝忘机的性格特点、喜好、习惯等，这些会影响他的回答方式"></textarea>
                </div>
            </div>
            <div class="modal-actions">
                <button class="modal-button save-button" onclick="saveCharacterSettings()">
                    <i class="fas fa-save"></i> 保存
                </button>
                <button class="modal-button cancel-button" onclick="closeModal('character-modal')">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
        </div>
    </div>

    <!-- 回复选项模态框 -->
    <div class="modal" id="response-modal">
        <div class="modal-content">
            <h3 class="modal-title">选择回复方式</h3>
            <div class="response-options" id="response-options">
                <!-- 选项会在这里动态添加 -->
            </div>
            <div class="modal-actions">
                <button class="modal-button cancel-button" onclick="closeModal('response-modal')">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
        </div>
    </div>

    <script>
        // 用户数据
        const userData = {
            name: '访客',
            identity: '',
            avatar: 'data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 100 100\'><circle cx=\'50\' cy=\'40\' r=\'20\' fill=\'%23e3f2fd\'/><path d=\'M30,70 Q50,90 70,70\' fill=\'%23e3f2fd\'/><rect x=\'40\' y=\'30\' width=\'20\' height=\'5\' fill=\'%230d47a1\'/><rect x=\'35\' y=\'50\' width=\'30\' height=\'5\' fill=\'%230d47a1\'/><path d=\'M40,25 Q50,15 60,25\' fill=\'none\' stroke=\'%230d47a1\' stroke-width=\'2\'/><circle cx=\'40\' cy=\'35\' r=\'3\' fill=\'%230d47a1\'/><circle cx=\'60\' cy=\'35\' r=\'3\' fill=\'%230d47a1\'/></svg>'
        };
        
        // AI数据
        const aiData = {
            avatar: 'data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 100 100\'><circle cx=\'50\' cy=\'40\' r=\'20\' fill=\'%23bbdefb\'/><path d=\'M30,70 Q50,90 70,70\' fill=\'%23bbdefb\'/><rect x=\'40\' y=\'30\' width=\'20\' height=\'5\' fill=\'%230d47a1\'/><rect x=\'35\' y=\'50\' width=\'30\' height=\'5\' fill=\'%230d47a1\'/><path d=\'M40,25 Q50,15 60,25\' fill=\'none\' stroke=\'%230d47a1\' stroke-width=\'2\'/><circle cx=\'40\' cy=\'35\' r=\'3\' fill=\'%230d47a1\'/><circle cx=\'60\' cy=\'35\' r=\'3\' fill=\'%230d47a1\'/></svg>',
            memory: [],
            character: {
                base: "蓝忘机，字忘机，号含光君，姑苏蓝氏二公子。为人清冷严肃，不苟言笑，恪守家规，雅正端方。佩剑避尘，法器忘机琴。与魏无羡关系密切。",
                additional: ""
            }
        };
        
        // 背景数据
        const bgData = {
            current: 'default',
            custom: null
        };
        
        // 音乐数据
        const musicData = {
            current: 'none',
            mode: 'loop',
            volume: 0.5,
            playing: false,
            playlist: ['guqin', 'xiao', 'pipa'],
            currentIndex: 0
        };
        
        // 天气和场景状态
        const sceneData = {
            weather: 'sunny',
            time: 'morning',
            location: 'cloudRecess'
        };
        
        // 消息历史
        let messageHistory = [];
        
        // 当前查看的头像类型
        let currentViewingAvatar = null;
        
        // 创建云朵和古琴飘动效果
        function createFloatingElements() {
            setInterval(() => {
                if (Math.random() > 0.7) {
                    const cloud = document.createElement('div');
                    cloud.className = 'cloud';
                    cloud.style.top = Math.random() * 100 + 'px';
                    cloud.style.animationDuration = (Math.random() * 20 + 20) + 's';
                    document.querySelector('.chat-container').appendChild(cloud);
                    
                    setTimeout(() => {
                        cloud.remove();
                    }, 30000);
                }
                
                if (Math.random() > 0.9) {
                    const guqin = document.createElement('div');
                    guqin.className = 'guqin';
                    guqin.style.top = Math.random() * 100 + 'px';
                    guqin.style.animationDuration = (Math.random() * 15 + 15) + 's';
                    document.querySelector('.chat-container').appendChild(guqin);
                    
                    setTimeout(() => {
                        guqin.remove();
                    }, 20000);
                }
            }, 3000);
        }
        
        // 发送消息
        function sendMessage() {
            const input = document.getElementById('message-input');
            const message = input.value.trim();
            
            if (message) {
                // 添加用户消息
                const userMessage = {
                    id: Date.now(),
                    content: message,
                    sender: 'user',
                    time: new Date(),
                    identity: userData.identity
                };
                
                addMessageToHistory(userMessage);
                renderMessages();
                input.value = '';
                
                // 显示AI正在输入
                document.getElementById('typing-indicator').style.display = 'flex';
                
                // 模拟AI思考时间
                setTimeout(() => {
                    document.getElementById('typing-indicator').style.display = 'none';
                    
                    // 生成AI回复
                    const aiResponse = generateAIResponse(message);
                    addMessageToHistory(aiResponse);
                    renderMessages();
                    
                    // 滚动到底部
                    const messagesContainer = document.getElementById('chat-messages');
                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                }, 1000 + Math.random() * 2000);
            }
        }
        
        // 添加消息到历史
        function addMessageToHistory(message) {
            messageHistory.push(message);
            // 记忆最近的5条对话
            if (message.sender === 'user') {
                aiData.memory.push(message.content);
                if (aiData.memory.length > 5) {
                    aiData.memory.shift();
                }
            }
        }
        
        // 渲染所有消息
        function renderMessages() {
            const messagesContainer = document.getElementById('chat-messages');
            messagesContainer.innerHTML = '';
            
            // 随机添加旁白
            if (Math.random() > 0.7 && messageHistory.length > 0) {
                const weatherDescriptions = {
                    sunny: ["阳光明媚", "和煦的阳光", "金色的阳光"],
                    cloudy: ["阴云密布", "天色阴沉", "乌云密布"],
                    rainy: ["细雨绵绵", "大雨滂沱", "雨丝飘落"]
                };
                
                const timeDescriptions = {
                    morning: ["清晨", "朝阳初升", "晨光熹微"],
                    noon: ["正午时分", "日上三竿", "午时"],
                    evening: ["傍晚", "夕阳西下", "黄昏时分"],
                    night: ["夜晚", "夜深人静", "皓月当空"]
                };
                
                const locationDescriptions = {
                    cloudRecess: ["云深不知处", "静室前", "兰室附近"],
                    lotusPier: ["莲花坞", "码头边", "练武场"],
                    koiTower: ["金麟台", "芳菲殿外", "金光瑶的书房附近"]
                };
                
                const weather = weatherDescriptions[sceneData.weather][Math.floor(Math.random() * weatherDescriptions[sceneData.weather].length)];
                const time = timeDescriptions[sceneData.time][Math.floor(Math.random() * timeDescriptions[sceneData.time].length)];
                const location = locationDescriptions[sceneData.location][Math.floor(Math.random() * locationDescriptions[sceneData.location].length)];
                
                const actions = [
                    "微风拂过，带来阵阵花香",
                    "几只仙鹤从空中飞过",
                    "远处传来弟子们的读书声",
                    "竹叶沙沙作响",
                    "琴音若有若无地飘来",
                    "一阵风吹动了蓝忘机的衣袖"
                ];
                
                const narrationText = `（${location}，${time}，${weather}，${actions[Math.floor(Math.random() * actions.length)]}）`;
                
                const narrationDiv = document.createElement('div');
                narrationDiv.className = 'narration';
                narrationDiv.textContent = narrationText;
                messagesContainer.appendChild(narrationDiv);
            }
            
            messageHistory.forEach((message, index) => {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${message.sender}-message`;
                messageDiv.dataset.id = message.id;
                
                const now = new Date(message.time);
                const timeString = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
                
                // 添加头像
                const avatarSrc = message.sender === 'user' ? userData.avatar : aiData.avatar;
                const avatarClick = message.sender === 'user' ? 'viewAvatar(userData.avatar)' : 'viewAvatar(aiData.avatar)';
                
                // 消息内容
                let contentHTML = message.content;
                if (message.sender === 'ai' && message.thought) {
                    contentHTML += `<div class="ai-thought">${message.thought}</div>`;
                }
                
                // 只有最新一条AI消息显示刷新按钮
                const showRefresh = message.sender === 'ai' && index === messageHistory.length - 1;
                
                messageDiv.innerHTML = `
                    <div class="message-avatar" onclick="${avatarClick}">
                        <img src="${avatarSrc}">
                    </div>
                    <div class="message-content">${contentHTML}</div>
                    <div class="message-time">${timeString}</div>
                    ${message.sender === 'user' ? 
                        `<div class="message-actions">
                            <div class="action-button" data-tooltip="删除" onclick="retractMessage(${message.id})">
                                <i class="fas fa-trash"></i>
                            </div>
                        </div>` : 
                        (showRefresh ? 
                            `<div class="back-button" onclick="backToMessage(${message.id})">
                                <i class="fas fa-undo"></i>
                            </div>
                            <div class="refresh-button" onclick="regenerateResponse(${message.id})">
                                <i class="fas fa-redo"></i>
                            </div>` : '')
                    }
                `;
                
                messagesContainer.appendChild(messageDiv);
            });
            
            // 滚动到底部
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
        
        // 回溯到指定消息
        function backToMessage(messageId) {
            const index = messageHistory.findIndex(msg => msg.id == messageId);
            if (index !== -1) {
                // 保留从开始到指定消息的所有消息
                messageHistory = messageHistory.slice(0, index + 1);
                renderMessages();
            }
        }
        
        // 查看头像
        function viewAvatar(avatarSrc) {
            document.getElementById('viewer-img').src = avatarSrc;
            document.getElementById('avatar-viewer').style.display = 'flex';
            
            // 设置当前查看的头像类型
            currentViewingAvatar = avatarSrc === aiData.avatar ? 'ai' : 'user';
        }
        
        // 删除当前查看的头像
        function deleteCurrentAvatar() {
            if (currentViewingAvatar === 'ai') {
                deleteAvatar('ai');
            } else {
                deleteAvatar('user');
            }
            closeModal('avatar-viewer');
        }
        
        // 生成蓝忘机风格的AI回复
        function generateAIResponse(userMessage) {
            // 关键词识别
            const greetingWords = ['你好', 'hi', 'hello', '您好', '哈喽'];
            const nameWords = ['名字', '称呼', '叫', '姓名'];
            const weiyingWords = ['魏婴', '魏无羡', '羡羡', '魏前辈'];
            const cloudWords = ['云深', '姑苏', '蓝氏', '家规'];
            const musicWords = ['琴', '音乐', '忘机', '清心', '问灵'];
            const drinkWords = ['酒', '天子笑', '喝酒', '醉'];
            const nightWords = ['夜', '晚上', '睡觉', '休息', '亥时'];
            const cultivationWords = ['修炼', '灵力', '金丹', '结婴', '剑法', '符咒'];
            const clanWords = ['江氏', '金氏', '聂氏', '温氏', '兰陵', '清河', '岐山'];
            const eventWords = ['夜猎', '除祟', '清谈会', '听学', '射日之征'];
            const animalWords = ['兔子', '灵犬', '仙鹤', '灵兽'];
            const placeWords = ['静室', '寒室', '兰室', '冷泉', '后山'];
            const itemWords = ['抹额', '避尘', '随便', '陈情', '阴虎符'];
            const tiantianWords = ['天天', '道侣', '双修', '结为道侣'];
            const intimateWords = ['想你', '喜欢', '爱', '心悦', '道侣'];
            
            // 蓝忘机常用语
            const commonResponses = [
                "嗯。",
                "......",
                "不可。",
                "不妥。",
                "不知。",
                "不必。",
                "无妨。",
                "随你。"
            ];
            
            const longerResponses = [
                "此事需从长计议。",
                "云深不知处禁酒。",
                "家规有云，不可妄言。",
                "修行之人，当谨言慎行。",
                "问灵十三载，等一不归人。",
                "我想带一人回云深不知处，带回去，藏起来。",
                "魏婴，别闹。",
                "此去小心。",
                "我在。",
                "你...很好。",
                "修行之道，贵在坚持。",
                "剑法需勤加练习。",
                "清心音可助静心凝神。",
                "夜猎需谨慎行事。",
                "云深不知处禁止疾行。",
                "抹额非父母妻儿不可触碰。",
                "冷泉有助于恢复灵力。",
                "后山的兔子...（欲言止）",
                "寒室清冷，但可静心。",
                "兰室藏书丰富，可多阅览。"
            ];
            
            // 根据用户消息生成回复
            let response = '';
            let thought = '';
            let options = [];
            
            // 检查用户身份
            const userIdentity = userData.identity;
            const isLanDisciple = userIdentity.includes('蓝氏');
            const isJiangDisciple = userIdentity.includes('江氏');
            const isJinDisciple = userIdentity.includes('金氏');
            const isNieDisciple = userIdentity.includes('聂氏');
            const isWenDisciple = userIdentity.includes('温氏');
            const isWeiying = userIdentity === '魏无羡';
            const isCultivator = userIdentity.includes('弟子') || userIdentity.includes('散修');
            
            // 问候语
            if (greetingWords.some(word => userMessage.includes(word))) {
                if (isWeiying) {
                    const responses = [
                        "魏婴...（耳尖微红）你回来了。",
                        "（放下手中书卷）魏婴，你...（欲言又止）",
                        "（琴弦微震）...魏婴。",
                        "（抬眼看你）...嗯。",
                        "（放下避尘剑）魏婴，别闹。"
                    ];
                    response = responses[Math.floor(Math.random() * responses.length)];
                    thought = "（魏婴主动打招呼...心跳加速）";
                } else if (isJiangDisciple) {
                    response = "嗯。（微微颔首）云梦江氏弟子来访，所为何事？";
                    thought = "（云梦江氏...魏婴的师门）";
                } else if (isJinDisciple) {
                    response = "嗯。兰陵金氏弟子，有何贵干？";
                    thought = "（金光瑶之事后，对金氏弟子需谨慎）";
                } else if (isNieDisciple) {
                    response = "嗯。清河聂氏弟子，请讲。";
                    thought = "（聂明玦之事...）";
                } else if (isWenDisciple) {
                    response = "......（神色冷淡）";
                    thought = "（温氏余孽？需警惕）";
                } else if (isCultivator) {
                    response = "嗯。阁下有何指教？";
                    thought = "（一位修行同道）";
                } else {
                    response = "嗯。（微微颔首）";
                    thought = "（看来是一位普通访客）";
                }
                options = [
                    response,
                    "姑苏蓝氏蓝忘机，见过阁下。",
                    "嗯。有事？",
                    "......（沉默不语）"
                ];
            } 
            // 询问名字
            else if (nameWords.some(word => userMessage.includes(word))) {
                response = "姑苏蓝氏蓝忘机，字忘机。";
                thought = "（询问我的身份...）";
                options = [
                    "你可以称呼我为含光君。",
                    "（整理衣袖）名字只是代号。",
                    "......（不愿多言）",
                    "（琴弦微震）"
                ];
            }
            // 提到魏无羡
            else if (weiyingWords.some(word => userMessage.includes(word))) {
                if (isWeiying) {
                    const responses = [
                        "魏婴...（耳尖泛红）你又在打什么主意？",
                        "（手中琴弦绷断）...魏婴。",
                        "（转身）...何事？",
                        "（抹额微乱）...你...",
                        "（呼吸一滞）...家规...家规有云..."
                    ];
                    response = responses[Math.floor(Math.random() * responses.length)];
                    thought = "（魏婴提到自己...他又想做什么？）";
                } else if (isJiangDisciple) {
                    response = "魏婴他...（眼神微动）是你们的师兄。";
                    thought = "（云梦江氏弟子提起魏婴...）";
                } else {
                    response = "魏婴他...（眼神微动）";
                    thought = "（提到魏婴...心中微动）";
                }
                options = [
                    "魏婴近来可好？",
                    "魏婴行事虽不拘小节，但...（停顿）心地纯善。",
                    "（琴弦微震）...魏婴。",
                    "他总是不守规矩。"
                ];
            }
            // 提到"天天"
            else if (tiantianWords.some(word => userMessage.includes(word))) {
                if (isWeiying) {
                    const responses = [
                        "魏婴！...（耳尖通红，别过脸去）不可胡言。",
                        "（手中避尘剑差点掉落）...魏婴，你...",
                        "（呼吸一滞）...家规...家规有云...",
                        "（转身就走）...不知羞。",
                        "（手中琴弦绷断）...你...",
                        "（抹额微乱）...白日...不可..."
                    ];
                    response = responses[Math.floor(Math.random() * responses.length)];
                    thought = "（魏婴又提这个...心跳加速）";
                } else {
                    response = "......（神色骤冷）";
                    thought = "（此人怎会知道这个...）";
                }
                options = [
                    "（转身就走）",
                    "家规有云，不可妄言。",
                    "（琴弦震响）",
                    "......（沉默不语）"
                ];
            }
            // 提到亲密话语
            else if (intimateWords.some(word => userMessage.includes(word))) {
                if (isWeiying) {
                    const responses = [
                        "魏婴...（耳尖通红）...你...",
                        "（手中书卷掉落）...不可妄言。",
                        "（呼吸急促）...你...当真？",
                        "（转身背对）...不知羞。",
                        "（琴弦绷断）...魏婴..."
                    ];
                    response = responses[Math.floor(Math.random() * responses.length)];
                    thought = "（魏婴说这种话...心跳如鼓）";
                } else {
                    response = "......（神色骤冷）";
                    thought = "（此人言行逾矩...）";
                }
                options = [
                    "（转身离去）",
                    "家规有云，不可妄言。",
                    "（琴弦震响）",
                    "......（沉默不语）"
                ];
            }
            // 提到云深不知处或家规
            else if (cloudWords.some(word => userMessage.includes(word))) {
                response = "云深不知处禁止喧哗。";
                thought = "（提及云深不知处...）";
                options = [
                    "家规三千条，需谨记于心。",
                    "姑苏蓝氏重雅正。",
                    "云深后山的兔子...（欲言止）",
                    "寒室清冷，但可静心。"
                ];
            }
            // 提到琴或音乐
            else if (musicWords.some(word => userMessage.includes(word))) {
                response = "忘机琴可问灵。";
                thought = "（对琴艺感兴趣？）";
                options = [
                    "（轻抚琴弦）你想听什么？",
                    "琴者，禁也。可修身理性，返其天真。",
                    "清心音可助静心凝神。",
                    "与魏婴合奏时...（停顿）音律甚谐。"
                ];
            }
            // 提到酒
            else if (drinkWords.some(word => userMessage.includes(word))) {
                if (isWeiying) {
                    const responses = [
                        "魏婴...（皱眉）你又偷喝酒了？",
                        "（叹气）...天子笑？",
                        "（摇头）...云深不知处禁酒。",
                        "（无奈）...魏婴，你..."
                    ];
                    response = responses[Math.floor(Math.random() * responses.length)];
                    thought = "（魏婴又喝酒...需看着他）";
                } else if (isJiangDisciple) {
                    response = "云深不知处禁酒。（想到魏婴也曾偷带天子笑）";
                    thought = "（云梦江氏弟子也爱喝酒？）";
                } else {
                    response = "云深不知处禁酒。";
                    thought = "（又有人提起酒...）";
                }
                options = [
                    "（皱眉）不可饮酒。",
                    "魏婴曾偷藏天子笑...（摇头）",
                    "醉酒易失仪态。",
                    "你...也想学魏婴喝酒？"
                ];
            }
            // 提到夜晚
            else if (nightWords.some(word => userMessage.includes(word))) {
                response = "亥时已至，该休息了。";
                thought = "（提及作息时间...）";
                options = [
                    "夜猎需谨慎。",
                    "（望向窗外）月色正好。",
                    "魏婴常夜不归宿...（语气微沉）",
                    "子时前需就寝。"
                ];
            }
            // 提到修炼相关
            else if (cultivationWords.some(word => userMessage.includes(word))) {
                if (isCultivator) {
                    response = "修行之道，贵在坚持。";
                    thought = "（同道讨论修行...）";
                } else {
                    response = "修行非一日之功。";
                    thought = "（普通人询问修行...）";
                }
                options = [
                    "剑法需勤加练习。",
                    "灵力运转需循经脉而行。",
                    "金丹稳固是修行基础。",
                    "（闭目调息）"
                ];
            }
            // 提到其他世家
            else if (clanWords.some(word => userMessage.includes(word))) {
                response = "各家自有其修行之道。";
                thought = "（讨论其他世家...）";
                options = [
                    "云梦江氏剑法飘逸灵动。",
                    "兰陵金氏重礼仪规范。",
                    "清河聂氏刀法刚猛。",
                    "（不愿多评）"
                ];
            }
            // 提到事件
            else if (eventWords.some(word => userMessage.includes(word))) {
                response = "夜猎需谨慎行事。";
                thought = "（提及修真界事件...）";
                options = [
                    "除祟需先查明缘由。",
                    "清谈会乃各家交流之所。",
                    "听学期间需遵守家规。",
                    "射日之征...（神色凝重）"
                ];
            }
            // 提到动物
            else if (animalWords.some(word => userMessage.includes(word))) {
                response = "后山养有灵兔数只。";
                thought = "（提及动物...）";
                options = [
                    "（想起魏婴喂兔子的情景）",
                    "仙鹤性洁，不喜喧闹。",
                    "灵犬...（想到魏婴怕狗）",
                    "灵兽需以诚心相待。"
                ];
            }
            // 提到地点
            else if (placeWords.some(word => userMessage.includes(word))) {
                response = "静室适合打坐修行。";
                thought = "（提及云深不知处地点...）";
                options = [
                    "冷泉有助于恢复灵力。",
                    "兰室藏书丰富，可多阅览。",
                    "后山景色...（停顿）尚可。",
                    "寒室清冷，但可静心。"
                ];
            }
            // 提到物品
            else if (itemWords.some(word => userMessage.includes(word))) {
                response = "抹额非父母妻儿不可触碰。";
                thought = "（提及重要物品...）";
                options = [
                    "避尘剑需定期养护。",
                    "（想到魏婴的随便剑）",
                    "陈情...（神色复杂）",
                    "阴虎符威力巨大，不可轻用。"
                ];
            }
            // 默认回复 - 基于上下文记忆
            else {
                // 检查是否有相关记忆
                const relatedMemory = aiData.memory.find(mem => 
                    mem.includes('魏婴') || mem.includes('云深') || mem.includes('修炼') || 
                    mem.includes('夜猎') || mem.includes('琴') || mem.includes('酒')
                );
                
                if (relatedMemory) {
                    if (relatedMemory.includes('魏婴')) {
                        response = "你方才也提到了魏婴...（眼神微动）";
                        thought = "（此人似乎对魏婴感兴趣）";
                        options = [
                            "魏婴近来可好？",
                            "（不愿多谈魏婴）",
                            "魏婴他...（欲言止）",
                            "......"
                        ];
                    } else if (relatedMemory.includes('云深')) {
                        response = "你似乎对云深不知处感兴趣。";
                        thought = "（继续云深不知处的话题）";
                        options = [
                            "云深不知处景色优美。",
                            "家规虽严，但有益修行。",
                            "（介绍云深不知处）",
                            "......"
                        ];
                    } else if (relatedMemory.includes('修炼')) {
                        response = "修行需持之以恒。";
                        thought = "（继续修行话题）";
                        options = [
                            "我可以指点你一二。",
                            "（演示剑法）",
                            "修行之道在于心。",
                            "......"
                        ];
                    } else {
                        // 70%概率简短回复，30%概率较长回复
                        if (Math.random() < 0.7) {
                            response = commonResponses[Math.floor(Math.random() * commonResponses.length)];
                        } else {
                            response = longerResponses[Math.floor(Math.random() * longerResponses.length)];
                        }
                        thought = "（思考如何回应）";
                    }
                } else {
                    // 70%概率简短回复，30%概率较长回复
                    if (Math.random() < 0.7) {
                        response = commonResponses[Math.floor(Math.random() * commonResponses.length)];
                    } else {
                        response = longerResponses[Math.floor(Math.random() * longerResponses.length)];
                    }
                    thought = "（思考如何回应）";
                }
                
                // 生成4个选项
                options = [
                    commonResponses[Math.floor(Math.random() * commonResponses.length)],
                    longerResponses[Math.floor(Math.random() * longerResponses.length)],
                    commonResponses[Math.floor(Math.random() * commonResponses.length)],
                    longerResponses[Math.floor(Math.random() * longerResponses.length)]
                ];
                options = [...new Set(options)]; // 去重
                while (options.length < 4) {
                    options.push(longerResponses[Math.floor(Math.random() * longerResponses.length)]);
                }
            }
            
            // 随机添加动作或心理描写
            const actions = [
                "（垂眸）",
                "（抬眼看你）",
                "（微微蹙眉）",
                "（指尖轻敲桌面）",
                "（整理衣袖）",
                "（琴弦微震）",
                "（耳尖微红）",
                "（轻叹一声）",
                "（望向远方）",
                "（闭目调息）"
            ];
            const randomAction = actions[Math.floor(Math.random() * actions.length)];
            
            // 根据身份添加不同语气
            if (isWeiying) {
                response += " " + randomAction;
                if (Math.random() > 0.7) {
                    thought = "（魏婴又来了...心跳加速）";
                }
            } else if (isJiangDisciple) {
                response += " " + randomAction + " 云梦江氏近来如何？";
            } else if (isJinDisciple) {
                response += " " + randomAction + " 兰陵金氏可好？";
            } else if (isNieDisciple) {
                response += " " + randomAction + " 聂宗主身体可还安好？";
            } else if (isWenDisciple) {
                response += " " + randomAction;
                thought = "（对温氏弟子保持警惕）";
            } else {
                response += " " + randomAction;
            }
            
            // 结合补充人设
            if (aiData.character.additional) {
                if (aiData.character.additional.includes("温柔")) {
                    response = response.replace("......", "（温和地）......");
                }
                if (aiData.character.additional.includes("严厉")) {
                    response = response.replace("嗯。", "嗯。（严肃地）");
                }
            }
            
            return {
                id: Date.now(),
                content: response,
                thought: thought,
                options: options,
                sender: 'ai',
                time: new Date()
            };
        }
        
        // 重新生成AI回复
        function regenerateResponse(messageId) {
            const messageIndex = messageHistory.findIndex(msg => msg.id == messageId);
            if (messageIndex !== -1 && messageHistory[messageIndex].sender === 'ai') {
                const prevMessage = messageHistory[messageIndex - 1];
                if (prevMessage && prevMessage.sender === 'user') {
                    // 找到刷新按钮并添加loading类
                    const refreshButton = document.querySelector(`.message[data-id="${messageId}"] .refresh-button`);
                    if (refreshButton) {
                        refreshButton.classList.add('loading');
                    }
                    
                    setTimeout(() => {
                        // 移除旧回复
                        messageHistory.splice(messageIndex, 1);
                        
                        // 生成新回复
                        const newResponse = generateAIResponse(prevMessage.content);
                        addMessageToHistory(newResponse);
                        renderMessages();
                        
                        // 滚动到底部
                        const messagesContainer = document.getElementById('chat-messages');
                        messagesContainer.scrollTop = messagesContainer.scrollHeight;
                    }, 500);
                }
            }
        }
        
        // 撤回消息
        function retractMessage(messageId) {
            const messageIndex = messageHistory.findIndex(msg => msg.id == messageId);
            if (messageIndex !== -1) {
                messageHistory.splice(messageIndex, 1);
                renderMessages();
            }
        }
        
        // 打开设置面板
        function toggleSettings() {
            const panel = document.getElementById('settings-panel');
            panel.style.display = panel.style.display === 'block' ? 'none' : 'block';
        }
        
        // 关闭所有模态框
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
            document.getElementById('settings-panel').style.display = 'none';
        }
        
        // 打开身份设置模态框
        function openIdentityModal() {
            document.getElementById('user-name').value = userData.name;
            document.getElementById('user-identity').value = userData.identity || '';
            document.getElementById('user-avatar-preview').src = userData.avatar;
            document.getElementById('identity-modal').style.display = 'flex';
        }
        
        // 保存身份设置
        function saveIdentity() {
            const name = document.getElementById('user-name').value.trim();
            const identity = document.getElementById('user-identity').value;
            
            if (name) {
                userData.name = name;
            }
            
            if (identity) {
                userData.identity = identity;
            }
            
            closeModal('identity-modal');
        }
        
        // 打开头像选择模态框
        function openAvatarModal(type) {
            if (type === 'user') {
                document.getElementById('avatar-modal-title').textContent = '选择你的头像';
                document.getElementById('avatar-modal').style.display = 'flex';
            } else {
                document.getElementById('ai-avatar-modal').style.display = 'flex';
            }
        }
        
        // 选择头像
        function selectAvatar(element, type) {
            const options = element.parentElement.querySelectorAll('.avatar-option');
            options.forEach(opt => opt.classList.remove('selected'));
            element.classList.add('selected');
        }
        
        // 上传头像
        function uploadAvatar(type) {
            const inputId = type === 'user' ? 'user-avatar-upload' : 'ai-avatar-upload';
            document.getElementById(inputId).click();
            
            document.getElementById(inputId).onchange = function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(event) {
                        const img = document.createElement('img');
                        img.src = event.target.result;
                        
                        if (type === 'user') {
                            document.querySelector('#avatar-modal .avatar-option.selected img').src = event.target.result;
                            document.getElementById('user-avatar-preview').src = event.target.result;
                        } else {
                            document.querySelector('#ai-avatar-modal .avatar-option.selected img').src = event.target.result;
                        }
                    };
                    reader.readAsDataURL(file);
                }
            };
        }
        
        // 保存头像
        function saveAvatar(type) {
            const selectedOption = document.querySelector(`#${type === 'user' ? 'avatar-modal' : 'ai-avatar-modal'} .avatar-option.selected`);
            if (selectedOption) {
                const imgSrc = selectedOption.querySelector('img').src;
                if (type === 'user') {
                    userData.avatar = imgSrc;
                } else {
                    aiData.avatar = imgSrc;
                    document.getElementById('ai-avatar').querySelector('img').src = imgSrc;
                }
                closeModal(type === 'user' ? 'avatar-modal' : 'ai-avatar-modal');
                renderMessages();
            }
        }
        
        // 删除头像
        function deleteAvatar(type) {
            if (type === 'user') {
                userData.avatar = 'data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 100 100\'><circle cx=\'50\' cy=\'40\' r=\'20\' fill=\'%23e3f2fd\'/><path d=\'M30,70 Q50,90 70,70\' fill=\'%23e3f2fd\'/><rect x=\'40\' y=\'30\' width=\'20\' height=\'5\' fill=\'%230d47a1\'/><rect x=\'35\' y=\'50\' width=\'30\' height=\'5\' fill=\'%230d47a1\'/><path d=\'M40,25 Q50,15 60,25\' fill=\'none\' stroke=\'%230d47a1\' stroke-width=\'2\'/><circle cx=\'40\' cy=\'35\' r=\'3\' fill=\'%230d47a1\'/><circle cx=\'60\' cy=\'35\' r=\'3\' fill=\'%230d47a1\'/></svg>';
            } else {
                aiData.avatar = 'data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 100 100\'><circle cx=\'50\' cy=\'40\' r=\'20\' fill=\'%23bbdefb\'/><path d=\'M30,70 Q50,90 70,70\' fill=\'%23bbdefb\'/><rect x=\'40\' y=\'30\' width=\'20\' height=\'5\' fill=\'%230d47a1\'/><rect x=\'35\' y=\'50\' width=\'30\' height=\'5\' fill=\'%230d47a1\'/><path d=\'M40,25 Q50,15 60,25\' fill=\'none\' stroke=\'%230d47a1\' stroke-width=\'2\'/><circle cx=\'40\' cy=\'35\' r=\'3\' fill=\'%230d47a1\'/><circle cx=\'60\' cy=\'35\' r=\'3\' fill=\'%230d47a1\'/></svg>';
                document.getElementById('ai-avatar').querySelector('img').src = aiData.avatar;
            }
            closeModal(type === 'user' ? 'avatar-modal' : 'ai-avatar-modal');
            renderMessages();
        }
        
        // 打开背景设置模态框
        function openBgModal() {
            document.getElementById('bg-modal').style.display = 'flex';
        }
        
        // 选择背景
        function selectBg(element, bgType) {
            const options = element.parentElement.querySelectorAll('.bg-option');
            options.forEach(opt => opt.classList.remove('selected'));
            element.classList.add('selected');
            bgData.current = bgType;
        }
        
        // 上传背景
        function uploadBg() {
            document.getElementById('bg-upload').click();
            
            document.getElementById('bg-upload').onchange = function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(event) {
                        bgData.custom = event.target.result;
                        const newOption = document.createElement('div');
                        newOption.className = 'bg-option selected';
                        newOption.onclick = function() { selectBg(this, 'custom'); };
                        newOption.innerHTML = '<img src="' + event.target.result + '">';
                        document.querySelector('.bg-options').appendChild(newOption);
                    };
                    reader.readAsDataURL(file);
                }
            };
        }
        
        // 保存背景
        function saveBg() {
            if (bgData.current === 'custom' && bgData.custom) {
                document.body.style.backgroundImage = `url('${bgData.custom}')`;
            } else {
                // 重置为默认背景
                document.body.style.backgroundImage = `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="400" height="600" viewBox="0 0 400 600"><rect width="400" height="600" fill="%23e6f7ff"/><path d="M0,300 Q100,250 200,300 Q300,350 400,300 L400,600 L0,600 Z" fill="%23bbdefb" opacity="0.3"/></svg>')`;
            }
            closeModal('bg-modal');
        }
        
        // 删除背景
        function deleteBg() {
            bgData.custom = null;
            const customBg = document.querySelector('.bg-options .bg-option:last-child');
            if (customBg) {
                customBg.remove();
            }
            document.body.style.backgroundImage = `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="400" height="600" viewBox="0 0 400 600"><rect width="400" height="600" fill="%23e6f7ff"/><path d="M0,300 Q100,250 200,300 Q300,350 400,300 L400,600 L0,600 Z" fill="%23bbdefb" opacity="0.3"/></svg>')`;
        }
        
        // 打开音乐设置模态框
        function openMusicModal() {
            document.getElementById('music-select').value = musicData.current;
            document.getElementById('music-mode').value = musicData.mode;
            document.getElementById('volume-control').value = musicData.volume;
            document.getElementById('music-modal').style.display = 'flex';
        }
        
        // 播放音乐
        function playMusic() {
            const music = document.getElementById('bg-music');
            music.volume = musicData.volume;
            music.play();
            musicData.playing = true;
        }
        
        // 暂停音乐
        function pauseMusic() {
            const music = document.getElementById('bg-music');
            music.pause();
            musicData.playing = false;
        }
        
        // 保存音乐设置
        function saveMusicSettings() {
            musicData.current = document.getElementById('music-select').value;
            musicData.mode = document.getElementById('music-mode').value;
            musicData.volume = parseFloat(document.getElementById('volume-control').value);
            
            const music = document.getElementById('bg-music');
            music.volume = musicData.volume;
            
            if (musicData.playing) {
                playMusic();
            }
            
            closeModal('music-modal');
        }
        
        // 打开角色设置模态框
        function openCharacterModal() {
            document.getElementById('character-info').value = aiData.character.additional;
            document.getElementById('character-modal').style.display = 'flex';
        }
        
        // 保存角色设置
        function saveCharacterSettings() {
            aiData.character.additional = document.getElementById('character-info').value;
            closeModal('character-modal');
        }
        
        // 处理键盘事件
        function handleKeyPress(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        }
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            createFloatingElements();
            
            // 设置音乐控制按钮事件
            document.getElementById('play-music').addEventListener('click', playMusic);
            document.getElementById('pause-music').addEventListener('click', pauseMusic);
            document.getElementById('volume-control').addEventListener('input', function() {
                document.getElementById('bg-music').volume = this.value;
            });
            
            // 设置身份选择框变化事件
            document.getElementById('user-identity').addEventListener('change', function() {
                document.getElementById('custom-identity').style.display = this.value === '' ? 'block' : 'none';
            });
            
            // 点击其他地方关闭设置面板
            document.addEventListener('click', function(e) {
                if (!e.target.closest('.settings-button') && !e.target.closest('.settings-panel')) {
                    document.getElementById('settings-panel').style.display = 'none';
                }
            });
        });
    </script>
</body>
</html>
<style>
    /* 更新回溯图标样式 */
    .back-button {
        position: absolute;
        bottom: -20px;
        right: 30px;
        width: 25px;
        height: 25px;
        border-radius: 50%;
        background-color: #f5f5f5;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        font-size: 12px;
        color: #555;
        border: 1px solid #ddd;
        z-index: 1;
    }
    
    /* 更新旋转图标样式 */
    .refresh-button {
        position: absolute;
        bottom: -20px;
        right: 0;
        width: 25px;
        height: 25px;
        border-radius: 50%;
        background-color: #f5f5f5;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        font-size: 12px;
        color: #555;
        border: 1px solid #ddd;
        z-index: 1;
    }
    
    /* 更新图标悬停提示位置 */
    .back-button:hover::after,
    .refresh-button:hover::after {
        content: attr(data-tooltip);
        position: absolute;
        top: -25px;
        left: 50%;
        transform: translateX(-50%);
        background-color: #333;
        color: white;
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 12px;
        white-space: nowrap;
    }
    
    /* 更新图标图标 */
    .back-button i {
        position: relative;
    }
    
    .back-button i::before {
        content: "≡";
        position: absolute;
        top: -5px;
        left: 0;
    }
    
    .back-button i::after {
        content: "↻";
        position: absolute;
        top: -5px;
        left: 0;
        font-size: 10px;
        transform: rotate(90deg);
    }
</style>

<!-- 在消息模板中更新图标部分 -->
<div class="message ai-message" data-id="1">
    <div class="message-avatar" onclick="viewAvatar(aiData.avatar)">
        <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><circle cx='50' cy='40' r='20' fill='%23bbdefb'/><path d='M30,70 Q50,90 70,70' fill='%23bbdefb'/><rect x='40' y='30' width='20' height='5' fill='%230d47a1'/><rect x='35' y='50' width='30' height='5' fill='%230d47a1'/><path d='M40,25 Q50,15 60,25' fill='none' stroke='%230d47a1' stroke-width='2'/><circle cx='40' cy='35' r='3' fill='%230d47a1'/><circle cx='60' cy='35' r='3' fill='%230d47a1'/></svg>">

</div>




<!-- 在<head>部分添加以下样式 -->
<style>
    /* 思考气泡样式 */
    .thinking-bubble {
        font-style: italic;
        color: #888;
        font-size: 0.8em;
        margin-top: 5px;
        margin-bottom: 10px;
        max-width: 80%;
    }
    
    /* 调整消息间距 */
    .message {
        margin-bottom: 15px;
    }
    
    /* 用户头像位置调整 */
    .user-message .avatar {
        position: absolute;
        right: -50px;
        top: -5px;
    }
    
    /* 蓝忘机头像位置调整 */
    .blue-message .avatar {
        position: absolute;
        left: -50px;
        top: -5px;
    }
    
    /* 下拉菜单样式 */
    .identity-select {
        padding: 8px;
        border-radius: 4px;
        border: 1px solid #ccc;
        background-color: white;
        margin-bottom: 15px;
    }
    
    /* 悬停显示操作按钮 */
    .message-actions {
        opacity: 0;
        transition: opacity 0.3s;
    }
    .message:hover .message-actions {
        opacity: 1;
    }
    
    /* 旋转图标悬停动画 */
    .loading-spinner:hover {
        animation: pulse 1s infinite;
    }
    @keyframes pulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.1); }
        100% { transform: scale(1); }
    }
</style>

<!-- 在JavaScript部分添加以下代码 -->

<!-- 增强记忆系统 - 存储对话历史 -->
<script>
// 在全局变量部分添加
const MAX_HISTORY_LENGTH = 50;
let conversationHistory = [];

// 添加对话到历史记录
function addToHistory(message, isUser) {
    conversationHistory.push({
        text: message,
        isUser: isUser,
        timestamp: new Date().getTime()
    });
    
    // 限制历史记录长度
    if (conversationHistory.length > MAX_HISTORY_LENGTH) {
        conversationHistory.shift();
    }
}

// 在发送消息函数中调用
function sendMessage() {
    const userMessage = document.getElementById('user-input').value;
    if (userMessage.trim() === '') return;
    
    // 显示用户消息
    displayMessage(userMessage, true);
    
    // 添加到历史记录
    addToHistory(userMessage, true);
    
    // 清空输入框
    document.getElementById('user-input').value = '';
    
    // 显示蓝忘机思考气泡
    const blueMessageDiv = document.createElement('div');
    blueMessageDiv.className = 'blue-message';
    blueMessageDiv.innerHTML = '<div class="thinking-bubble">蓝忘机正在思考...</div>';
    document.getElementById('chat-container').appendChild(blueMessageDiv);
    scrollToBottom();
    
    // 模拟蓝忘机思考延迟
    setTimeout(() => {
        // 从历史记录获取上下文
        const context = getRecentContext();
        
        // 生成回复（这里应该是调用你的AI逻辑）
        const response = generateResponse(userMessage, context);
        
        // 移除思考气泡
        document.getElementById('chat-container').removeChild(blueMessageDiv);
        
        // 显示蓝忘机回复
        displayMessage(response, false);
        
        // 添加到历史记录
        addToHistory(response, false);
    }, 1000);
}

// 获取最近的对话上下文
function getRecentContext() {
    // 返回最近的对话记录，可以限制数量
    return conversationHistory.slice(-20); // 例如取最近的20条
}

// 在generateResponse函数中（需要你自己实现或修改现有的）
function generateResponse(userMessage, context) {
    // 这里应该实现你的AI逻辑，使用context来生成更连贯的回复
    // 简单示例:
    let response = "这是蓝忘机的回复";
    
    // 根据上下文调整回复...
    // 例如检查是否提到魏无羡等
    
    return response;
}
</script>

<!-- 用户身份反应系统 -->
<script>
// 在全局变量部分添加
let currentUserIdentity = 'visitor'; // 默认身份

// 处理身份选择
document.getElementById('identity-select').addEventListener('change', function() {
    currentUserIdentity = this.value;
    // 可以在这里添加身份切换后的其他逻辑
});

// 在generateResponse函数中考虑用户身份
function generateResponse(userMessage, context) {
    let response = "这是蓝忘机的回复";
    
    // 根据用户身份调整回复
    if (currentUserIdentity === 'weiwuxian') {
        // 魏无羡的特殊回复逻辑
        if (userMessage.includes('魏无羡')) {
            response = "看到你提到自己，蓝忘机微微一笑，眼中闪过温柔的光芒...";
        } else if (userMessage.includes('忘机')) {
            response = "蓝忘机听到你呼唤他的名字，眼神微动，轻声道：'我在。'";
        }
        // 可以添加更多情侣相处模式的回复
    }
    
    // 其他身份的回复逻辑...
    
    return response;
}
</script>

<!-- 剧情丰富化 - 关键词识别和场景处理 -->
<script>
// 在全局变量部分添加
const Keywords = {
    '魏无羡': handleWeiWuXianMention,
    '修真界': handleCultivationWorldMention,
    // 可以添加更多关键词
};

// 处理消息中的关键词
function processKeywords(message) {
    for (const keyword in Keywords) {
        if (message.includes(keyword)) {
            Keywords[keyword](message);
        }
    }
}

// 处理提到魏无羡的情况
function handleWeiWuXianMention(message) {
    // 可以设置一个标志，让generateResponse函数知道提到了魏无羡
    // 例如: window.mentionedWeiWuXian = true;
}

// 处理提到修真界的情况
function handleCultivationWorldMention(message) {
    // 可以设置一个标志，让generateResponse函数知道提到了修真界
}

// 修改generateResponse函数以考虑关键词
function generateResponse(userMessage, context) {
    // 处理关键词
    processKeywords(userMessage);
    
    let response = "这是蓝忘机的回复";
    
    // 根据关键词和上下文生成回复...
    
    return response;
}
</script>

<!-- 交互改进 - 下拉菜单替换身份选择 -->
<script>
// 在HTML部分应该已经将原来的身份选择改为下拉菜单
// 这里添加对应的事件处理
</script>

<!-- 删除不需要的功能 -->
<!-- 
1. 已删除点击蓝忘机回复上图片点击可以查看头像或者自由上传头像的功能
2. 已删除保存与删除选项功能
3. 已删除用户消息撤回功能(改为蓝忘机回复重新说并提供4个选择)
4. 已删除显示用户新修攻图片在用户回复上的功能
-->

<!-- 注意: 以下功能需要根据您的具体实现进行调整 -->

<!-- 蓝忘机回复重新说并提供4个选择的实现 -->
<script>
// 在generateResponse函数中添加特殊处理
function generateResponse(userMessage, context) {
    // 检查是否需要提供4个选择(例如用户消息撤回后)
    if (window.needProvideChoices) {
        // 生成4个选择项
        const choices = [
            "选项1: 蓝忘机可能会这样回答...",
            "选项2: 蓝忘机可能会这样回答...",
            "选项3: 蓝忘机可能会这样回答...",
            "选项4: 蓝忘机可能会这样回答..."
        ];
        
        // 创建选择UI
        let responseHTML = '<div class="choices-container">';
        choices.forEach(choice => {
            responseHTML += `<div class="choice-option" onclick="selectChoice('${choice}')">${choice}</div>`;
        });
        responseHTML += '</div>';
        
        return responseHTML;
    }
    
    // 正常回复逻辑...
    return "这是蓝忘机的回复";
}

// 选择选项的处理
function selectChoice(choiceText) {
    // 处理用户选择的选项
    displayMessage(choiceText, false);
    // 可能需要重置needProvideChoices标志
    window.needProvideChoices = false;
}
</script>

